<?php
namespace app\admin\controller;

use app\common\BaseAdminController;
use app\common\Result;
use app\model\Product as ModelProduct;
use app\validate\Product as ValidateProduct;
use think\facade\Db;

class Product extends BaseAdminController
{
    public function list($pageNum = 1, $pageSize = 10, $categoryId = null, $name = "")
    {
        $storeId = $this->request->storeId;
        if (empty($storeId)) {
            return Result::error('店铺ID不能为空');
        }
        // 分页查询所有商品
        // $query = Db::table('product')->where("store_id", $storeId)->whereLike("name", "%$name%");
        $query = ModelProduct::with(['category'])->where("store_id", $storeId)->whereLike("name", "%$name%");
        $total = Db::table('product')->where("store_id", $storeId)->whereLike("name", "%$name%")->count(); // 获取总记录数

        if ($categoryId) {
            $query->where("category_id", $categoryId);                                                                                           // 过滤指定分类的商品
            $total = Db::table('product')->where(["store_id" => $storeId, "category_id" => $categoryId])->whereLike("name", "%$name%")->count(); // 获取总记录数
        }

        $list = $query->page($pageNum, $pageSize)->select();

        return Result::success([
            'list'  => $list,
            'total' => $total,
        ], '查询成功');
    }

    public function add()
    {
        // 接收data
        $data = $this->request->post();
        // 验证数据
        $validate = new ValidateProduct();
        if (! $validate->check($data)) {
            return Result::error($validate->getError());
        }

        // 判断名称是否重复
        $product = \app\model\Product::where('name', $data['name'])->find();
        if ($product) {
            return Result::error('商品名称已存在');
        }

        // 使用模型创建数据
        $product = new \app\model\Product();
        // 设置店铺ID
        $product->store_id = $this->request->storeId;

        $result = $product->save($data);

        if ($result) {
            return Result::success(null, '添加成功');
        }

        return Result::error('添加失败');
    }

    public function update()
    {
        // 接收data
        $data = $this->request->post();
        // 验证数据
        $validate = new ValidateProduct();
        if (! $validate->check($data)) {
            return Result::error($validate->getError());
        }

        // 判断名称是否重复
        $product = \app\model\Product::where('name', $data['name'])->find();
        if ($product && $product->id != $data['id']) {
            return Result::error('商品名称已存在');
        }

        // 使用模型更新数据
        $product = \app\model\Product::find($data['id']);
        if (! $product) {
            return Result::error('商品不存在');
        }

        $result = $product->save($data);

        if ($result) {
            return Result::success(null, '更新成功');
        }

        return Result::error('更新失败');
    }
}
